package com.zimo.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 *
 * @author Administrator
 *	获取连接
 */
public class Connection implements Utils{
    /**
     *
     * @param url   下载地址
     * @param followRedirects   是否让当前连接跟随重定向
     * @return HttpURLConnection
     * @throws IOException
     *
     * 获取连接
     */
    public static HttpURLConnection getConnection(URL url,boolean followRedirects) throws IOException {
        //创建新连接
        //获取HttpURLConnection 链接对象
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        //设置请求头
        conn.setRequestProperty("accept", "application/octet-stream");
        conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1");

        //设置参数  发送get请求
        conn.setRequestMethod("GET"); //默认请求 就是get  要大写

        //设置此次连接自动跟随URL重定向
        conn.setInstanceFollowRedirects(followRedirects);

        //设置链接网络的超时时间
        conn.setConnectTimeout(15*1000);
        return conn;
    }

    /**
     * 获取网络输入流
     * @param url   下载链接
     */
    public static InputStream getInputStream(URL url) throws IOException {
        return  getConnection(url,false).getInputStream(); //网络输入流
    }

    /**
     * 判断服务器是否支持分段下载
     */
    public  static  boolean isSupportThread(URL url) throws IOException {
        HttpURLConnection con = getConnection(url, false);
        con.setRequestProperty("Range", "bytes="+0+"-"+0);
        if (con.getResponseCode() == 206) return true;
        return false;
    }
}
